"use client";
import CreateModal from "./components/CreateModal";
import UpdateModal from "./components/UpdateModal";
import {
    batchDeleteQuestionsUsingPost,
    deleteQuestionUsingPost,
    listQuestionByPageUsingPost,
} from "@/api/questionController";
import { PlusOutlined, ExclamationCircleOutlined, RobotOutlined } from "@ant-design/icons";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import { Button, message, Popconfirm, Space, Table, Typography, Modal, Tooltip } from "antd";
import React, { useRef, useState } from "react";
import TagList from "@/components/TagList";
import MdEditor from "@/components/MdEditor";

import UpdateBankModal from "@/app/admin/question/components/UpdateBankmodel";
import BatchRemoveQuestionsFromBankModal from "@/app/admin/question/components/BatchRemoveQuestionsFromBankModal";
import BatchAddQuestionsToBankModal from "@/app/admin/question/components/BatchAddQuestionsToBankModal";
import "./index.css";
import AIGenerateModal from "@/app/admin/question/components/AIGenerateModal";

const { confirm } = Modal;

/**
 * 题目管理页面
 *
 * @constructor
 */
const QuestionAdminPage: React.FC = () => {
    // 是否显示新建窗口
    const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
    // 是否显示更新窗口
    const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
    // 是否显示更新所属题库窗口
    const [updateBankModalVisible, setUpdateBankModalVisible] =
        useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    // 当前题目点击的数据
    const [currentRow, setCurrentRow] = useState<API.Question>();
    // 是否显示批量向题库添加题目弹窗
    const [
        batchAddQuestionsToBankModalVisible,
        setBatchAddQuestionsToBankModalVisible,
    ] = useState<boolean>(false);
    // 是否显示批量从题库移除题目弹窗
    const [
        batchRemoveQuestionsFromBankModalVisible,
        setBatchRemoveQuestionsFromBankModalVisible,
    ] = useState<boolean>(false);
    // 当前选中的题目 id 列表
    const [selectedQuestionIdList, setSelectedQuestionIdList] = useState<
        number[]
    >([]);
    // 当前分页信息
    const [paginationConfig, setPaginationConfig] = useState({
        current: 1,
        pageSize: 10,
    });
    // 是否显示 AI 生成题目弹窗
    const [aiGenerateModalVisible, setAiGenerateModalVisible] = useState<boolean>(false);


    /**
     * 删除节点
     *
     * @param row
     */
    const handleDelete = async (row: API.Question) => {
        const hide = message.loading("正在删除");
        if (!row) return true;
        try {
            await deleteQuestionUsingPost({
                id: row.id as any,
            });
            hide();
            message.success("删除成功");

            // 刷新表格
            actionRef?.current?.reload();
            return true;
        } catch (error: any) {
            hide();
            message.error("删除失败，" + error.message);
            return false;
        }
    };

    /**
     * 显示删除确认对话框
     * @param row
     */
    const showDeleteConfirm = (row: API.Question) => {
        confirm({
            title: '确认删除题目',
            icon: <ExclamationCircleOutlined />,
            content: `确定要删除题目"${row.title}"吗？此操作不可恢复。`,
            okText: '确认删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                return handleDelete(row);
            },
        });
    };

    /**
     * 批量删除
     * @param questionIdList
     */
    const handleBatchDelete = async (questionIdList: number[]) => {
        const hide = message.loading("正在操作");
        try {
            await batchDeleteQuestionsUsingPost({
                questionIdList,
            });
            hide();
            message.success("操作成功");

            // 刷新表格
            actionRef?.current?.reload();
        } catch (error: any) {
            hide();
            message.error("操作失败，" + error.message);
        }
    };

    /**
     * 显示批量删除确认对话框
     * @param questionIdList
     */
    const showBatchDeleteConfirm = (questionIdList: number[]) => {
        confirm({
            title: '确认批量删除',
            icon: <ExclamationCircleOutlined />,
            content: `确定要删除选中的 ${questionIdList.length} 个题目吗？此操作不可恢复。`,
            okText: '确认删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                return handleBatchDelete(questionIdList);
            },
        });
    };

    // @ts-ignore
    // @ts-ignore
    // @ts-ignore
    /**
     * 表格列配置
     */
    const columns: ProColumns<API.Question>[] = [
        {
            title: "ID",
            dataIndex: "id",
            valueType: "text",
            hideInForm: true,
            width: 60,
            fixed: 'left',
        },
        {
            title: "标题",
            dataIndex: "title",
            valueType: "text",
            ellipsis: true,
            width: 200,
            render: (text) => (
                <Tooltip title={text}>
                    <span>{text}</span>
                </Tooltip>
            ),
        },
        {
            title: "内容",
            dataIndex: "content",
            valueType: "text",
            hideInSearch: true,
            width: 240,
            render: (_, record) => (
                <Typography.Paragraph ellipsis={{ rows: 2 }} style={{ margin: 0, maxWidth: 240 }}>
                    {record.content?.replace(/<[^>]*>/g, '')}
                </Typography.Paragraph>
            ),
            renderFormItem: (item, { fieldProps }, form) => {
                return <MdEditor {...fieldProps} />;
            },
        },
        {
            title: "答案",
            dataIndex: "answer",
            valueType: "text",
            hideInSearch: true,
            width: 240,
            render: (_, record) => (
                <Typography.Paragraph ellipsis={{ rows: 2 }} style={{ margin: 0, maxWidth: 240 }}>
                    {record.answer?.replace(/<[^>]*>/g, '')}
                </Typography.Paragraph>
            ),
            renderFormItem: (item, { fieldProps }, form) => {
                return <MdEditor {...fieldProps} />;
            },
        },
        {
            title: "标签",
            dataIndex: "tags",
            valueType: "select",
            fieldProps: {
                mode: "tags",
            },
            width: 180,
            render: (_, record) => {
                const tagList = JSON.parse(record.tags || "[]");
                return <TagList tagList={tagList} maxCount={3} />;
            },
        },
        {
            title: "创建用户",
            dataIndex: "userId",
            valueType: "text",
            hideInForm: true,
            width: 100,
        },
        {
            title: "创建时间",
            sorter: true,
            dataIndex: "createTime",
            valueType: "dateTime",
            hideInSearch: true,
            hideInForm: true,
            width: 150,
        },
        {
            title: "编辑时间",
            sorter: true,
            dataIndex: "editTime",
            valueType: "dateTime",
            hideInSearch: true,
            hideInForm: true,
            width: 150,
        },
        {
            title: "更新时间",
            sorter: true,
            dataIndex: "updateTime",
            valueType: "dateTime",
            hideInSearch: true,
            hideInForm: true,
            width: 150,
        },
        {
            title: "操作",
            dataIndex: "option",
            valueType: "option",
            fixed: 'right',
            width: 200,
            render: (_, record) => (
                <Space size="middle">
                    <Typography.Link
                        onClick={() => {
                            setCurrentRow(record);
                            setUpdateModalVisible(true);
                        }}
                        className="action-link"
                    >
                        修改
                    </Typography.Link>
                    <Typography.Link
                        onClick={() => {
                            setCurrentRow(record);
                            setUpdateBankModalVisible(true);
                        }}
                        className="action-link"
                    >
                        修改所属题库
                    </Typography.Link>
                    <Typography.Link
                        type="danger"
                        onClick={() => showDeleteConfirm(record)}
                        className="action-link danger"
                    >
                        删除
                    </Typography.Link>
                </Space>
            ),
        },
    ];

    return (
        <PageContainer className="question-admin-page">
            <ProTable<API.Question>
                headerTitle={"题目管理"}
                actionRef={actionRef}
                rowKey="id"
                scroll={{ x: 1500 }}
                rowSelection={{
                    selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                    defaultSelectedRowKeys: [],
                }}
                tableAlertRender={({
                    selectedRowKeys,
                    selectedRows,
                    onCleanSelected,
                }) => {
                    return (
                        <Space size={24} className="selection-alert">
                            <span>
                                已选 {selectedRowKeys.length} 项
                                <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                                    取消选择
                                </a>
                            </span>
                        </Space>
                    );
                }}
                tableAlertOptionRender={({
                    selectedRowKeys,
                    selectedRows,
                    onCleanSelected,
                }) => {
                    return (
                        <Space size={16} className="batch-actions">
                            <Button
                                onClick={() => {
                                    setSelectedQuestionIdList(selectedRowKeys as number[])
                                    setBatchAddQuestionsToBankModalVisible(true);
                                }}
                                className="batch-btn"
                            >
                                批量向题库添加题目
                            </Button>
                            <Button
                                onClick={() => {
                                    setSelectedQuestionIdList(selectedRowKeys as number[])
                                    setBatchRemoveQuestionsFromBankModalVisible(true);
                                }}
                                className="batch-btn"
                            >
                                批量从题库移除题目
                            </Button>
                            <Button
                                danger
                                onClick={() => showBatchDeleteConfirm(selectedRowKeys as number[])}
                                className="batch-btn danger"
                            >
                                批量删除题目
                            </Button>
                        </Space>
                    );
                }}
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            setCreateModalVisible(true);
                        }}
                        icon={<PlusOutlined />}
                        className="create-btn"
                    >
                        新建题目
                    </Button>,
                    <Button
                        key="ai-generate"
                        onClick={() => setAiGenerateModalVisible(true)}
                        icon={<RobotOutlined />}
                    >
                        AI 生成题目
                    </Button>,
                ]}
                request={async (params, sort, filter) => {
                    const sortField = Object.keys(sort)?.[0];
                    const sortOrder = sort?.[sortField] ?? undefined;

                    // 获取当前分页参数
                    const { current, pageSize } = params;

                    // 更新本地分页配置
                    setPaginationConfig({
                        current: current || 1,
                        pageSize: pageSize || 10,
                    });

                    // @ts-ignore
                    const { data, code } = await listQuestionByPageUsingPost({
                        ...params,
                        sortField,
                        sortOrder,
                        ...filter,
                        current,
                        pageSize,
                    } as API.QuestionQueryRequest);

                    return {
                        success: code === 0,
                        data: data?.records || [],
                        total: Number(data?.total) || 0,
                    };
                }}
                columns={columns}
                pagination={{
                    // 使用 ProTable 内部的分页管理
                    showSizeChanger: true,
                    showQuickJumper: true,
                    pageSizeOptions: ['10', '20', '50', '100'],
                    showTotal: (total, range) =>
                        `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                }}
                // 处理分页变化
                onChange={(pagination, filters, sorter, extra) => {
                    // 这里可以处理分页变化时的逻辑
                    // 但不需要更新状态，因为 ProTable 会内部处理
                }}
            />
            <CreateModal
                visible={createModalVisible}
                columns={columns}
                onSubmit={() => {
                    setCreateModalVisible(false);
                    actionRef.current?.reload();
                }}
                onCancel={() => {
                    setCreateModalVisible(false);
                }}
            />
            <UpdateModal
                visible={updateModalVisible}
                columns={columns}
                oldData={currentRow}
                onSubmit={() => {
                    setUpdateModalVisible(false);
                    setCurrentRow(undefined);
                    actionRef.current?.reload();
                }}
                onCancel={() => {
                    setUpdateModalVisible(false);
                }}
            />
            <UpdateBankModal
                visible={updateBankModalVisible}
                questionId={currentRow?.id}
                onCancel={() => {
                    setUpdateBankModalVisible(false);
                }}
                onSuccess={() => {
                    setUpdateBankModalVisible(false);
                    actionRef.current?.reload();
                }}
            />
            <BatchAddQuestionsToBankModal
                visible={batchAddQuestionsToBankModalVisible}
                questionIdList={selectedQuestionIdList}
                onSubmit={() => {
                    setBatchAddQuestionsToBankModalVisible(false);
                    actionRef.current?.reload();
                }}
                onCancel={() => {
                    setBatchAddQuestionsToBankModalVisible(false);
                }}
            />
            <BatchRemoveQuestionsFromBankModal
                visible={batchRemoveQuestionsFromBankModalVisible}
                questionIdList={selectedQuestionIdList}
                onSubmit={() => {
                    setBatchRemoveQuestionsFromBankModalVisible(false);
                    actionRef.current?.reload();
                }}
                onCancel={() => {
                    setBatchRemoveQuestionsFromBankModalVisible(false);
                }}
            />
            <AIGenerateModal
                visible={aiGenerateModalVisible}
                onSubmit={() => {
                    setAiGenerateModalVisible(false);
                    // 生成完成后刷新表格（保留当前分页）
                    actionRef.current?.reload();
                }}
                onCancel={() => setAiGenerateModalVisible(false)}
            />
        </PageContainer>
    );
};
export default QuestionAdminPage;